package zero.mybatisplus.dynamictable.util;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import zero.mybatisplus.dynamictable.param.DynamicTableParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class DynamicTableUtil {
    private static final ThreadLocal<SimpleDateFormat> YYYY_MM_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMM"));

    /**
     * 获取动态表名
     *
     * @param dynamicTableParam
     * @return 拼接好的表名
     */
    public static String getDynamicTableName(DynamicTableParam dynamicTableParam) {
        //时间分区处理
        String dateValue = handleDateValueStr(dynamicTableParam.getDateValue());
        String tableName = dynamicTableParam.getTableName();
        switch (dynamicTableParam.getType()) {
            case YEAR_TABLE:
                if (StringUtils.isNotBlank(dateValue)) {
                    tableName = tableName + dateValue.substring(0, 4);
                }
                break;
            case YEAR_MONTH_TABLE:
                if (StringUtils.isNotBlank(dateValue)) {
                    tableName = tableName + dateValue.substring(0, 6);
                }
                break;
        }
        return tableName;
    }

    /**
     * 处理时间分区字段值成字符串
     *
     * @param dateValue
     * @return
     */
    public static String handleDateValueStr(Object dateValue) {
        if (Objects.isNull(dateValue)) {
            return null;
        }
        if (dateValue instanceof Date) {
            return YYYY_MM_FORMAT.get().format(dateValue) + "01";
        } else {
            String s = String.valueOf(dateValue);
            String s1 = s.replaceAll(StringPool.DASH, "").replaceAll(StringPool.SLASH, "");
            if (StringUtils.isNotBlank(s1)) {
                if (s1.length() >= 8) {
                    return s1.substring(0, 6) + "01";
                } else if (s1.length() == 6) {
                    return s1 + "01";
                } else if (s1.length() == 4) {
                    return s1 + "0101";
                }
            }
            return null;
        }
    }
}
